package com.harven.maplite.complier;

import com.google.auto.service.AutoService;
import com.harven.maplite.annotation.BindView;

import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;

/**
 * MapLiteAnnotationProcessor
 *
 * @author harven
 * @date 2021/11/23 15:43
 */
@AutoService(Processor.class)
@SupportedAnnotationTypes({ "com.harven.maplite.annotation.BindView" })
public class MapLiteAnnotationProcessor extends AbstractProcessor {

    Messager messager;
    Elements elements;
    Filer filer;

    @Override
    public synchronized void init(ProcessingEnvironment env) {
        super.init(env);
        messager = env.getMessager();
        Map<String, String> options = env.getOptions();
        messager.printMessage(Diagnostic.Kind.NOTE, String.format("options:%s", options));
        elements = env.getElementUtils();
        filer = env.getFiler();
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    /**
     * {@inheritDoc}
     *
     * @param annotations
     * @param env
     */
    @Override
    public boolean process(Set<? extends TypeElement> annotations,
                           RoundEnvironment env) {
        messager.printMessage(Diagnostic.Kind.NOTE, "MapLiteAnnotationProcessor start processing...");
        Set<? extends Element> elements = env.getElementsAnnotatedWith(BindView.class);
        for (Element element : elements) {
            VariableElement ele = ((VariableElement) element);
            TypeElement classEle = (TypeElement)ele.getEnclosingElement();
            CharSequence className = classEle.getQualifiedName();
            BindView bindView = ele.getAnnotation(BindView.class);
            int id = bindView.value();
            messager.printMessage(Diagnostic.Kind.NOTE, String.format("[element:%s %s]", ele.getClass(), ele));
            messager.printMessage(Diagnostic.Kind.NOTE, String.format("[  class:%s %s className:%s %s]", classEle.getClass(), classEle, className.getClass(), className));
        }


        return false;
    }
}
